--[[
    Author          ZhengFeng
    Time            2020.12.05
    Description     宠物拟变界面-拟变成功
]]--
require "Common/define"
require "Logic/PetManager"

local Page_PetMatingSuccess = UIBase.New(PanelResNames.Page_PetMatingSuccess)
local this = Page_PetMatingSuccess
local partListIndex = 0
local isMatingType = 0;
function this.Init(matingType)
    isMatingType = matingType;
    UIBase.Init(this)
end

function this:OnCreate()
    self.Btn_BGClose = self:GetChild("Btn_BGClose")
    self.Txt_PetName = self:GetChild("Txt_PetName")
    self.List_Part = self:GetChild("List_Part")
    self.List_Part.itemRenderer = this.renderPartListItem
    self.Model_Pet = self:GetChild("Model_Pet")
    self.EffectWrapTarget = self:GetChild("SpecialEffect").wrapTarget
    self.ShowTypeController = self:GetController("ShowType")
    self.Txt_CurrentLevel2 = self:GetChild("Txt_CurrentLevel2")
    self.Txt_ExpNumber2 = self:GetChild("Txt_ExpNumber2")
    self.upLevelController = self:GetController("levelup");
    self.ProgressBar_Exp2 = self:GetChild("ProgressBar_Exp2")
    self.nextDec = self:GetChild("text4");
    self.matingTypeController = self:GetController("matingType");
    self.progressIdle = self:GetChild("Effect_LevelUp1");
    self.upLevelIdle = self:GetChild("Effect_LevelUp2");

    this.partChangeLists = {};

    self:RegisterOnClick(self.Btn_BGClose, self.onClickClose)
end

function this:OnEnable()
    this:showSpecialEffect()

    self.isProgress = false;

end

function this:OnDisable()
    self.List_Part.numItems = 0
    this:closeTimer()
    this:removePetModel()
end
function this:OnDestroy()
    this:removePetModel()
end

function this:onClickClose()
    if self.EffectWrapTarget.activeSelf then
        this:showNewBornPet()
    else
        if self.isProgressEnd then
            PetManager.NewBornPetId = 0
            this:removePetModel()
            closeUI(PanelResNames.Page_PetMatingSuccess)
        end
    end
end
function this:showSpecialEffect()
    if PetManager.NewBornPetId ~= 0 then
        self.matingTypeController.selectedIndex = isMatingType;
        if this.petTimer == nil then
            self.Txt_PetName.text = ""
            self.EffectWrapTarget:SetActive(true)
            if PetManager.isQuickMating then
                this:showNewBornPet()
            else
                self.ShowTypeController:SetSelectedIndex(1)
                Util.PlayAction(self.EffectWrapTarget, "idle", false)
                local _duration = PetManager.NewPetSpecialEffectDuration
                this.petTimer = utimer.timeCall(function()
                    this:showNewBornPet()
                end, _duration, 1)
            end
        else
            this:showNewBornPet()
        end
    end
end
function this:closeTimer()
    if this.petTimer then
        utimer.remove(this.petTimer)
    end
    this.petTimer = nil
end
function this:refreshPetEvoLevelProgress()
    if self.isProgress then
        return
    end
    self.isProgress = true;
    self.Txt_CurrentLevel2.text = string.format(getLanguage("Level"), PetManager.EvoLevel);
    local lastLevelCfg = G.dataTable["t_elvesevolevel"][tostring(PetManager.EvoLevel - 1)]
    local curEvoLevelCfg = G.dataTable["t_elvesevolevel"][tostring(PetManager.EvoLevel)]
    local nextEvoLevelCfg = G.dataTable["t_elvesevolevel"][tostring(PetManager.EvoLevel + 1)]
    local sumExp = 0;
    for i = 1, PetManager.EvoLevel do
        local cfg = G.dataTable["t_elvesevolevel"][tostring(i)]
        sumExp = sumExp + cfg["f_Exp"];
    end
    local curExp = PetManager.EvoLevelExp ;
    if nextEvoLevelCfg == nil then
        self.Txt_ExpNumber2.text = "Max";
        self.ProgressBar_Exp2.value = 100;
    else
        self.Txt_ExpNumber2.text = ((curExp / nextEvoLevelCfg["f_Exp"]) * 100) .. "%";
        self.ProgressBar_Exp2.value = (curExp / nextEvoLevelCfg["f_Exp"]) * 100;
    end

    self.upLevelController = PetManager.isEvoLvUp;
    local lastExp = curExp - 1;
    if PetManager.isEvoLvUp == 1 then
        self.Txt_CurrentLevel2.text = string.format(getLanguage("Level"), (PetManager.EvoLevel - 1));

        PetManager.isEvoLvUp = 0;
        local lastSumExp = curEvoLevelCfg["f_Exp"]
        lastExp = lastSumExp - 1;
        if lastExp <= 0 then
            lastExp = 0;
        end
        local changes = (1 / 10);
        self.Txt_ExpNumber2.text = ((lastExp / curEvoLevelCfg["f_Exp"]) * 100) .. "%";
        self.ProgressBar_Exp2.value = (lastExp / curEvoLevelCfg["f_Exp"]) * 100;
        self.nextDec.text = getLanguage(curEvoLevelCfg.f_TalentDesc)
        local count = 0;

        utimer.timeCall(function()
            lastExp = lastExp + changes;
            count = count + 1;
            self.Txt_ExpNumber2.text = math.ceil((lastExp / curEvoLevelCfg["f_Exp"]) * 100) .. "%";
            self.ProgressBar_Exp2.value = (lastExp / curEvoLevelCfg["f_Exp"]) * 100;
            if count >= 10 then
                --升级

                local effectShow = self.progressIdle.spineAnimation.state;
                effectShow:SetAnimation(0, "idle", false);

                local lvUpShow = self.upLevelIdle.spineAnimation.state;
                lvUpShow:SetAnimation(0, "idle2", false);
                self.nextDec.text = getLanguage(nextEvoLevelCfg.f_TalentDesc)
                local idleAniTime = lvUpShow.Data.SkeletonData:FindAnimation("idle").Duration;
                self.uTimer = utimer.timeCall(function()
                    --effect.visible = false;
                    utimer.remove(self.uTimer);
                    self.isProgressEnd = true;

                end, idleAniTime * 1000)

                self.Txt_ExpNumber2.text = "0%";
                self.ProgressBar_Exp2.value = 0;
                self.Txt_CurrentLevel2.text = string.format(getLanguage("Level"), PetManager.EvoLevel);
            end
        end, 0.05, 10)

    else
        if nextEvoLevelCfg then
            local changes = 1 / 10;
            self.Txt_ExpNumber2.text = ((lastExp / nextEvoLevelCfg["f_Exp"]) * 100) .. "%";
            self.ProgressBar_Exp2.value = (lastExp / nextEvoLevelCfg["f_Exp"]) * 100;
            local count = 0;

            utimer.timeCall(function()
                lastExp = lastExp + changes;
                count = count + 1;

                self.Txt_ExpNumber2.text = math.ceil((lastExp / nextEvoLevelCfg["f_Exp"]) * 100) .. "%";
                self.ProgressBar_Exp2.value = (lastExp / nextEvoLevelCfg["f_Exp"]) * 100;
                if count >= 10 then
                    local effectShow = self.progressIdle.spineAnimation.state;
                    effectShow:SetAnimation(0, "idle", false);
                    local idleAniTime = effectShow.Data.SkeletonData:FindAnimation("idle").Duration;
                    self.uTimer = utimer.timeCall(function()
                        --effect.visible = false;
                        utimer.remove(self.uTimer);
                        self.isProgressEnd = true;

                    end, idleAniTime * 1000)
                end
            end, 0.05, 10)
            self.nextDec.text = getLanguage(nextEvoLevelCfg.f_TalentDesc)
        end
    end
end

function this:showNewBornPet()
    self.ShowTypeController:SetSelectedIndex(0)
    self.EffectWrapTarget:SetActive(false)
    if PetManager.NewBornPetId ~= 0 then
        local _petInfo = PetManager.GetPetInfoByPetId(PetManager.NewBornPetId)
        local lastPetInfo = _petInfo.geneticMap[2];

        this.partChangeLists = {};
        for i = 1, #_petInfo.genes do
            local oldId = lastPetInfo.genes[i];
            local newId = _petInfo.genes[i];
            if oldId ~= newId then
                local idChange = {}
                idChange[1] = oldId;
                idChange[2] = newId;
                table.insert(this.partChangeLists, idChange)
            end

        end

        self.Txt_PetName.text = _petInfo.petName

        partListIndex = 0
        self.List_Part.numItems = #self.partChangeLists

        this:showPetModel()
        if isMatingType == 0 then
            this:refreshPetEvoLevelProgress()
        else
            self.isProgressEnd = true;
        end

    end
end
function this:renderPartListItem(obj)
    partListIndex = partListIndex + 1
    local _petInfo = PetManager.GetPetInfoByPetId(PetManager.NewBornPetId)
    local oldItem = obj:GetChild("Btn_BeforePart");
    local newItem = obj:GetChild("Btn_AfterPart");
    local changePart = this.partChangeLists[partListIndex];

    local ctrlItem = CtrlManager.GetCtrl(PanelNames.PetPartItem);
    ctrlItem.initData(oldItem, changePart[1]);
    ctrlItem.initData(newItem, changePart[2]);
    local cfg = G.dataTable["t_elvesgene"][tostring(changePart[2])];
    if cfg.f_MutationLevel > 1 then
        obj:GetController("type").selectedIndex = 1;
    else
        obj:GetController("type").selectedIndex = 0;
    end
    --local _geneId = _petInfo.genes[partListIndex]
    --local _geneConfig = G.dataTable["t_elvesgene"]
    --local _geneInfo = _geneConfig[tostring(_geneId)]
    --local _partName = getLanguage(_geneInfo.f_GeneName)
    --
    --local Txt_title = obj:GetChild("title")
    --Txt_title.text = _partName
    --
    --local _petMutationLevel = _geneInfo.f_MutationLevel
    --obj:GetController("level"):SetSelectedIndex(_petMutationLevel-1)
end

--显示宠物模型
function this:removePetModel()
    if this.PetModelGO then
        destroyImmediate(this.PetModelGO)
    end
    this.PetModelGO = nil
end
function this:showPetModel()
    local _petInfo = PetManager.GetPetInfoByPetId(PetManager.NewBornPetId)
    if _petInfo and #_petInfo.genes == PetManager.PetPart.Ornament then
        local _petModelInfo = {}
        _petModelInfo.parentGO = this.Model_Pet
        _petModelInfo.petId = _petInfo.petId
        if this.PetModelGO and this.goWrapper then
            _petModelInfo.modelGO = this.PetModelGO
            _petModelInfo.modelWrapper = this.goWrapper
            PetManager.PetModelRefresh(_petModelInfo, _petInfo.genes, true)
        else
            this:removePetModel()
            resMgr:LoadModelPrefab(PetManager.PetModelPrefab, function(go)
                this.PetModelGO = newObject(go)

                local com = this.PetModelGO:GetComponent("SkeletonGraphic")

             if this.PetModelGO and com then
                 com.material = resMgr.Pet_Copy_Mat
                 com.material:SetFloat("_StencilComp",8)
                 com.material:SetFloat("_Stencil",1);
             end

                local _modelWrapper = this.goWrapper
                this.goWrapper = GoWrapper.New()
                _petModelInfo.modelGO = this.PetModelGO
                _petModelInfo.modelWrapper = this.goWrapper
                PetManager.PetModelFirstSet(_petModelInfo, _petInfo.genes, true, Vector3.New(0, 0, 0), Vector3.New(3, 3, 1))
                if _modelWrapper then
                    _modelWrapper:Dispose()
                end
            end)
        end
    end
end
return this